<?php

namespace App\Models;

use App\Common\Constant\Params;
use App\Services\IMasterService;
use App\Services\IStorageService;
use Carbon\Carbon;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Collection;

class Order extends BaseModel
{

    use Notifiable;

    protected $table = 'orders';

    const CREATED_AT = 'add_time';
    const UPDATED_AT = 'upd_time';

    protected $dateFormat = 'U';

    protected $fillable = [
        'order_number',
        'merchant_id',
        'service_category',
        'service_type',
        'confirm_code',
        'push_time',
        'master_id',
        'offer_price',
        'merchant_price',
        'appoint_time',
        'pay_time'
    ];

    protected $casts = [
        'offer_price' => 'double',
        'merchant_price' => 'double',
        'push_time' => 'datetime',
        'appoint_time' => 'datetime',
        'pay_time' => 'datetime',
    ];

    protected $appends = ['cover_img_url','offering_endtime'];

    public function detail(){
        return $this->hasOne(OrderDetail::class,'order_id');
    }

    public function goods(){
        return $this->hasMany(OrderGoods::class,'order_id');
    }

    public function status(){
        return $this->hasOne(OrderStatus::class,'order_id');
    }

    public function refunds(){
        return $this->hasMany(OrderRefund::class,'order_id');
    }

    public function getRefundAttribute(){
        return $this->refunds->first();
    }

    public function offers(){
        return $this->hasMany(OrderOffer::class,'order_id');
    }

    public function evaluate(){
        return $this->hasOne(OrderEvaluate::class,'oe_orderid');
    }

    public function complain(){
        return $this->hasOne(OrderComplain::class,'oc_orderid');
    }

    public function master()
    {
        return $this->belongsTo(Master::class,'master_id');
    }

    public function merchant(){
        return $this->belongsTo(Merchant::class,'merchant_id');
    }

    public function replenishs()
    {
        return $this->hasMany(OrderReplenish::class,'order_id')->where(function ($query){
            $query->whereNotNull('pay_time')
                ->where('pay_time','<>','');
        });
    }

    /**
     * 获取应该支付师傅的金额
     * master_money
     */
    public function getMasterMoneyAttribute()
    {
        return $this->offer_price;
    }

    /**
     * 获取商家应该支付的预付款金额
     * merchant_pay_money
     */
    public function getMerchantPayMoneyAttribute()
    {
        return $this->merchant_price ? : $this->offer_price*(1+config('common.earn_percent_per_order'));
    }

    /**
     * 获取系统应该抽成的金额
     * system_money
     */
    public function getSystemMoneyAttribute()
    {
        return $this->merchant_price - $this->offer_price;
    }

    /**
     * 获取对应付款成功记录
     * merchant_trade_log
     */
    public function getMerchantTradeLogAttribute(){
        return MerchantTradeLog::where('status',Params::TRADE_STATUS_SUCCESS)->whereRaw('FIND_IN_SET(?,order_number_list)', [$this->id])->first();
    }

    /**
     * 获取服务类型文本
     */
    public function getServiceTypeTextAttribute()
    {
        return Params::$MERCHANT_SERVICE_TYPE[$this->service_type];
    }

    /**
     * 获取匹配师傅的服务类型文本
     */
    public function getMasterServiceTypeTextAttribute()
    {
        return Collection::make(resolve(IMasterService::class)->transformMerchantServiceType($this->service_type))->transform(function($item,$key){
            return Params::$SERVICE_TYPE[$item];
        })->implode('+');
    }

    /**
     * 订单封面图
     */
    public function getCoverImgUrlAttribute()
    {
        $firstGoods = OrderGoods::where('order_id',$this->attributes[$this->primaryKey])->orderBy(self::CREATED_AT)->first();
        if ($firstGoods){
            return $firstGoods->goods_img_url;
        }
    }

    /**
     * 报价截止时间
     */
    public function getOfferingEndtimeAttribute()
    {
        $end_time = $this->push_time->addDays(config('common.order_offering_endtime'));
        if ($end_time->lte(Carbon::now())){
            return $end_time->format('Y-m-d H:i:s');
        }

        $rest_time = $end_time->timestamp - time();
        $text = '';
        $hours = intval($rest_time/3600);
        if ($hours){
            $text .= "{$hours}小时";
            $rest_time -= 3600*$hours;
        }
        $minutes = intval($rest_time/60);
        if ($minutes){
            $text .= "{$minutes}分";
        }else if (empty($text)){
            $text = ' < 1分钟';
        }
        return $text;
    }

    /**
     * 补款金额总和
     * replenish_total
     */
    public function getReplenishTotalAttribute()
    {
        return $this->replenishs->sum('replenish_amount');
    }
}
